﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Innovation
{
    // Manages a PhysicsObject and allows the engine to work
    // with it
    public class PhysicsActor : Actor
    {
        // The object we are managing
        public PhysicsObject PhysicsObject;

        public override void Update()
        {
            transform = PhysicsObject.Transform;
            base.Update();
        }

        // Override the BoundingBox of the base class to that
        // of the physics object
        public override BoundingBox BoundingBox 
        { 
            get {
                if (PhysicsObject != null)
                    return PhysicsObject.BoundingBox;
                else
                    return new BoundingBox(-Vector3.One, Vector3.One);
            } 
        }

        // Constructors

        public PhysicsActor() 
        {
        }

        public PhysicsActor(string Model, PhysicsObject PhysicsObject) 
            : base(Model, PhysicsObject.Transform.Position) 
        {
            this.PhysicsObject = PhysicsObject;
            transform = PhysicsObject.Transform;
        }

        public PhysicsActor(string Model, PhysicsObject PhysicsObject, GameScreen Parent) 
            : base(Model, PhysicsObject.Transform.Position, Parent)
        {
            this.PhysicsObject = PhysicsObject;
            transform = PhysicsObject.Transform;
        }

        // Override DisableComponent so we can remove the physics
        // object as well
        public override void DisableComponent()
        {
            this.PhysicsObject.DisableComponent();
            base.DisableComponent();
        }

        public override void SaveSerializationData(SerializationData Data)
        {
            base.SaveSerializationData(Data);

            if (PhysicsObject != null)
                Data.AddData("PhysicsActor.PhysicsObject", PhysicsObject.Name);
        }

        public override void LoadFromSerializationData(SerializationData Data)
        {
            base.LoadFromSerializationData(Data);

            if (Data.ContainsData("PhysicsActor.PhysicsObject"))
            {
                string physicsObject = Data.GetData<string>("PhysicsActor.PhysicsObject");

                foreach (GameScreen screen in Engine.GameScreens)
                    foreach (Component component in screen.Components)
                        if (component.Name == physicsObject)
                            this.PhysicsObject = (PhysicsObject)component;
            }
        }
    }
}
